package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.mapper.ShoppingCartMapper;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.utils.BaseContext;
import com.itheima.reggie.utils.Result;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Resource
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    public Result<ShoppingCart> addShoppingCart(ShoppingCart shoppingCart) {
        // 查询当前用户的购物车中是否有该商品
        Long userId = BaseContext.getCurrentId();
        String name = shoppingCart.getName();
        String dishFlavor = shoppingCart.getDishFlavor();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId)
                .eq(ShoppingCart::getName, name);
        ShoppingCart commodity = shoppingCartMapper.selectOne(queryWrapper);
        // 当前用户的购物车中有该商品
        if (commodity != null) {
            commodity.setNumber(commodity.getNumber() + 1);
            shoppingCartMapper.updateById(commodity);
            return Result.success(commodity);
        }
        // 当前用户的购物车中没有该商品
        shoppingCart.setUserId(userId);
        shoppingCart.setNumber(1);
        shoppingCart.setCreateTime(LocalDateTime.now());
        shoppingCartMapper.insert(shoppingCart);
        return Result.success(shoppingCart);
    }

    @Override
    public Result<List<ShoppingCart>> getShoppingCartList() {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId)
                .orderByAsc(ShoppingCart::getCreateTime);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(queryWrapper);
        return Result.success(shoppingCartList);
    }

    @Override
    public Result<String> cleanShoppingCart() {
        // 获取当前用户id
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId,userId);
        shoppingCartMapper.delete(queryWrapper);
        return Result.success("购物车清空成功");
    }
}
